<template>
    <div>
        <el-form>
            <el-table border :data="arrdata" style="margin: 10px 0;">
                <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
                <el-table-column label="属性名称" align="center" prop="saleAttrName"></el-table-column>
                <el-table-column label="属性值名称" align="center">
                    <template #="{ row, $index }">
                        <el-tag type="success" v-for="(item, i) in row.spuSaleAttrValueList" :key="item.id"
                            style="margin: 3px;" closable>{{ item.saleAttrValueName }}

                        </el-tag>
                    </template>
                </el-table-column>
            </el-table>
            <el-form-item label="SPU名称">
                <el-input placeholder="请输入SPU名称" v-model="spuParams.spuName"></el-input>
            </el-form-item>
            <el-form-item label="SPU品牌">
                <el-select v-model="spuParams.tmId">
                    <el-option v-for="item in allTradeMark" :key="item.id" :label="item.tmName"
                        :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="SPU描述">
                <el-input type="textarea" placeholder="请输入SPU描述" :rows="2" v-model="spuParams.description"></el-input>
            </el-form-item>
            <el-form-item label="SPU照片">
                <el-upload v-model:file-list="imgList" action="/api/admin/product/fileUpload" list-type="picture-card"
                    :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :before-upload="beforeUpload">
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>

            <el-form-item label="SPU销售属性">
                <el-select style="margin-right: 10px;" :placeholder="unSelectSaleAttr.length ? '请选择销售属性' : '暂无属性供选择'"
                    v-model="saleAttrIdAndValueName">
                    <el-option v-for="item in unSelectSaleAttr" :key="item.id" :label="item.name"
                        :value="`${item.id}:${item.name}`" />
                </el-select>
                <el-button type="primary" icon="Plus" :disabled="saleAttrIdAndValueName ? false : true"
                    @click="addSaleAttr">添加属性值</el-button>
                <el-table border style="margin:10px 0;" :data="saleAttr">
                    <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
                    <el-table-column label="销售属性名称" prop="saleAttrName" align="center"></el-table-column>
                    <el-table-column label="销售属性值" align="center">
                        <template #="{ row, $index }">
                            <el-tag type="success" v-for="(item, i) in row.spuSaleAttrValueList" :key="item.id"
                                style="margin: 3px;" closable @close="row.spuSaleAttrValueList.splice(i, 1)">{{

                                    item.saleAttrName }}</el-tag>
                            <el-input v-if="row.flag" v-model="row.saleAttrValue" style="width: 150px;" size="small"
                                placeholder="请输入属性值" @blur="toLook(row, $index)" :ref="(el) => (inputArr[$index] = el)" />
                            <el-button v-else type="primary" size="small" icon="Plus"
                                @click="toEdit(row, $index)"></el-button>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120px" align="center">
                        <template #="{ row }">
                            <el-popconfirm :title="`确定要删除 ${row.saleAttrName} 吗?`" icon="DeleteFilled" icon-color="#f56c6c"
                                @confirm="saleAttr.splice(saleAttr.indexOf(row), 1)">
                                <template #reference>
                                    <el-button type="danger" size="small" icon="Delete" />
                                </template>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>

            </el-form-item>

            <el-form-item>
                <el-button type="primary" size="default" @click="save">保存</el-button>
                <el-button type="primary" size="default" @click="cancel">取消</el-button>
            </el-form-item>
        </el-form>
        <!-- 照片墙 -->
        <el-dialog v-model="dialogVisible" width="35%">
            <el-image :src="currentImg" style="width: 100%; height: 100%;" fit="cover"></el-image>
        </el-dialog>
    </div>
</template>
<script setup>
import { getTrademarkList, getSpuImageListAPI, getSpuSaleAttrListAPI, getAllSaleAttrAPI, addsaveSpuInfo, updateSpuInfo } from '@/api/product/spu/index.js'
import { ref, computed, nextTick } from 'vue'
let $emit = defineEmits(['changeScene'])
const cancel = () => {
    $emit('changeScene', { flag: 0, state: '' })
}
let arrdata = ref([])
// 存储已有的SPU数据
let allTradeMark = ref([])
// 存储已有的SPU图片数据
let imgList = ref([])
// 存储已有的SPU销售属性数据
let saleAttr = ref([])
// 存储已有的销售属性数据
let allSaleAttr = ref([])
// 收集还未先择的销售属性ID和属性值的名字
let saleAttrIdAndValueName = ref('')
// 输入框的所有实例对象
let inputArr = ref([])
// 存储已有spu对象
const spuParams = ref({
    category3Id: '',
    spuName: '',
    description: '',
    tmId: '',
    spuImageList: [],
    spuSaleAttrList: [],
})
// 计算出当前SPU还为拥有的销售属性
let unSelectSaleAttr = computed(() => {
    return allSaleAttr.value.filter(item => (
        saleAttr.value.every(sale => item.name !== sale.saleAttrName)
    ))
})
const imgLoading = ref(false)
const initHasSpuData = async (row) => {
    // 存储已有spu对象
    spuParams.value = row
    imgLoading.value = true
    console.log(row);
    const res = await Promise.all([
        getTrademarkList(),
        getSpuImageListAPI((row.id)),
        getSpuSaleAttrListAPI((row.id)),
        getAllSaleAttrAPI()
    ])
    allTradeMark.value = res[0].data
    imgList.value = res[1].data.map(item => ({ name: item.imgName, url: item.imgUrl }))
    saleAttr.value = res[2].data
    allSaleAttr.value = res[3].data

    // 全部品牌数据
    // let result = await getTrademarkList()
    // console.log(result);
    // // 获取某个sku的图片列表
    // let result1 = await getSpuImageListAPI(row.id)
    // console.log(result1);
    // let result2 = await getSpuSaleAttrListAPI(row.id)
    // console.log(result2);
    // // 某个 spu 销售属性
    // let result3 = await getAllSaleAttrAPI()
    // console.log(result3);
    // allTradeMark.value = result.data
    // // imgList.value = result1.data
    // imgList.value = result1.data.map(item => ({ name: item.imgName, url: item.imgUrl }))
    // // 存储已有的SPU销售属性数据
    // saleAttr = result2.data
    // arrdata = result2.data
    // console.log(saleAttr);
    // // 存储已有的销售属性数据
    // allSaleAttr = result3.data

}
// 预览图片对话框的显示与隐藏
let dialogVisible = ref(false)
let currentImg = ref('')
// 照片墙点击预览
const handlePictureCardPreview = (e) => {
    console.log(e)
    currentImg.value = e.url
    dialogVisible.value = true
}
// 照片墙删除某一个
const handleRemove = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
}
// 图片上传之前的钩子
const beforeUpload = (rawFile) => {
    // 允许的图片格式
    const allowedImageType = ['image/jpg', 'image/jpeg', 'image/png', 'image/gif']
    if (!allowedImageType.includes(rawFile.type)) {
        ElMessage.error('图片必须是JPG|PNG|GIF格式!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 4) {
        ElMessage.error('图片大小不能超过4MB!')
        return false
    }
    return true
}
const toEdit = (row, i) => {
    console.log(22);
    // 点击按钮显示input
    row.flag = true
    row.saleAttrValue = ''

    nextTick(() => {
        inputArr.value[i].focus()
    })
}
const toLook = (row, i) => {
    // 整理收集到的数据
    const { baseSaleAttrId, saleAttrValue } = row
    let newSaleAttrValue = {
        baseSaleAttrId,
        saleAttrName: saleAttrValue
    }

    // 非法情况1
    if ((saleAttrValue).trim() === '') {
        row.flag = false
        return ElMessage.warning('属性值不能为空')
    }

    // 判断属性值是否在数组中存在
    let repeat = row.spuSaleAttrValueList.find(item => item.saleAttrName === saleAttrValue)
    if (repeat) {
        ElMessage.warning('属性值已存在')
        nextTick(() => {
            inputArr.value[i].select()
        })
        return
    }

    // 追加新的属性值
    row.spuSaleAttrValueList.push(newSaleAttrValue)
    row.flag = false
}
const addSaleAttr = () => {
    console.log(212);
    const [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(':')
    // 准备新的销售属性对象
    let newSaleAttr = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: []
    }
    // 追加到数组中
    saleAttr.value.push(newSaleAttr)
    // 清空收集的数据
    saleAttrIdAndValueName.value = ''
}
const save = async () => {
    // 有ID修改没ID增加
    if (spuParams.value.id) {
        spuParams.value.spuImageList = imgList.value.map(item => ({
            imgName: item.name,
            imgUrl: (item.response && item.response.data) || item.url
        }))
        // 2.销售属性数据整理
        spuParams.value.spuSaleAttrList = saleAttr.value
        console.log(spuParams.value);
        // 发请求：添加SPU|修改SPU
        const res = await updateSpuInfo(spuParams.value)
        //   console.log(res);
        if (res.code === 200) {
            ElMessage.success(res.message)
            $emit('changeScene', { flag: 0, state: 'update' })
        } else {
            ElMessage.error(res.message)
        }
    }
    //    增加
    else {
        spuParams.value.spuImageList = imgList.value.map(item => ({
            imgName: item.name,
            imgUrl: (item.response && item.response.data) || item.url
        }))
        // 2.销售属性数据整理
        spuParams.value.spuSaleAttrList = saleAttr.value
        console.log(spuParams.value);
        // 发请求：添加SPU|修改SPU
        const res = await addsaveSpuInfo(spuParams.value)
        console.log(res);
        if (res.code === 200) {
            ElMessage.success(res.message)
            $emit('changeScene', { flag: 0, state: 'update' })
        } else {
            ElMessage.error(res.message)
        }
        console.log(222);
    }
    // 整理参数
    // 1.照片墙数据整理

}
// 添加一个新的 SPU 初始化请求方法
const initAddSpu = async (id) => {
    console.log(id);
    // 清空数据
    Object.assign(spuParams.value, {
        category3Id: '',
        id: '',
        spuName: '',
        description: '',
        tmId: '',
        spuImageList: [],
        spuSaleAttrList: [],
    })
    // 清空照片
    imgList.value = []
    // 清空销售属性
    saleAttr.value = []
    saleAttrIdAndValueName.value = ''

    // 存储三级分类id
    spuParams.value.category3Id = id
    // 获取全部品牌数据
    const res = await Promise.all([
        getTrademarkList(),
        getAllSaleAttrAPI()
    ])
    allTradeMark.value = res[0].data
    allSaleAttr.value = res[1].data
}
defineExpose({
    initHasSpuData,
    initAddSpu
});
</script>
<style lang="scss">
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>